<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>用户登录</title>
</head>

<body>
  <!-- <form action="/login" method="post" enctype="multipart/form-data"> -->
  <form action="/login" method="post" enctype="application/x-www-form-urlencoded">
    <div>
      <input type="text" name="username">
    </div>
    <div>
      <input type="text" name="password">
    </div>
    <div>
      <input type="hidden" name="avatar" id="avatar">
      <input type="file" onchange="changeFile(this)">
    </div>
    <div>
      <button type="submit">用户登录</button>
    </div>
  </form>
  <script>
    function changeFile(fileDom) {
      // formData -- 如果用它来完成文件上传它的表单类型为 multipart/form-data
      let formData = new FormData()
      // formData.append('name', '1.jpg')
      // 得到当前的上传的文件对象
      let file = fileDom.files[0]
      let reader = new FileReader()
      reader.readAsArrayBuffer(file)
      reader.onloadend = function () {
        // reader.result 它也是一个buffer数据
        // formData.append('file', reader.result)
        // 异步网络请求
        let xhr = new XMLHttpRequest()
        xhr.open('post', '/upfile', true)
        xhr.setRequestHeader('filename', file.name)
        xhr.onreadystatechange = function () {
          if (xhr.readyState == 4 && xhr.status == 200) {
            // console.log(xhr.responseText)
            let { data: { url } } = JSON.parse(xhr.responseText)
            document.querySelector('#avatar').value = url
          }
        }
        // application/x-www-form-urlencoded  标准类型  数据流
        xhr.send(reader.result)
      }

    }
  </script>
</body>

</html>